import { Toast } from 'antd-mobile'
import {reqlogin} from '../../request/api'
//初始状态
const initState={
        user:{
                phone:'',
                password:''
        },
        //用户登录的信息
        // userinfo:{}
        //一进页面，判断本地存储中是否有存数据，有就取出来，没有就{}
        userinfo:localStorage.getItem('isLogin')?JSON.parse(localStorage.getItem('isLogin')):{}
}

//TYPES
const TYPES={
        CHANGE_LOGIN:'CHANGE_LOGIN',
        //修改用户信息
        CHANGE_LOGIN_USER:' CHANGE_LOGIN_USER'
}

//reducer
const reducer =(state=initState,action)=>{
        switch(action.type){
                // {type:'CHANGE_LOGIN',key"111",value:'111'}
                case TYPES.CHANGE_LOGIN:
                        return{
                                ...state,
                                user:{
                                        ...state.user,
                                        [action.key]:action.value
                                }
                        }
                case TYPES.CHANGE_LOGIN_USER:
                        return{
                                ...state,
                                userinfo:action.userinfo
                        }
                default:
                        return state
        }
}

//creators 做逻辑 方法  请求
export const actions={
        changeUsers:(key,value)=>({type:TYPES.CHANGE_LOGIN,key,value}),
        //修改用户信息
        changeinfo:(userinfo)=>{
                //判断用户userinfo中有没token，有存，没有删
                if(userinfo.token){
                        localStorage.setItem('isLogin',JSON.stringify(userinfo))
                }else{
                        localStorage.removeItem('isLogin')
                }
                
               return {type:TYPES.CHANGE_LOGIN_USER,userinfo}
        },
        //点击登录发送请求
        doLogin:(push)=>{
                return (dispatch,getState)=>{
                        let user=getUsers(getState())
                        reqlogin(user).then(res=>{
                                if(res.data.code==200){
                                        Toast.show({
                                                content:res.data.msg
                                        })
                                //存用户信息
                                dispatch(actions.changeinfo(res.data.list))
                                //跳转首页
                                push('/index/home')
                                }
                        })
                }
        }
}

// 导出数据给组件
export const getUsers=(state)=>state.login.user

//导出userinfo用户信息
export const getuserinfo=(state)=>state.login.userinfo
// 导出reducer
export default reducer